from datetime import timedelta
from pathlib import Path

from celery import platforms


BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = 'kr+nxluty#f&nusxilr88)_7*gb%pxfh0mmg0lb#2l4fz6!j20'
JWT_SIGNING_KEY = '&c%=x^b40ezn-=upa!jtn&c3doxls#fbc)s)5)eeb*q%=x^eb'

DEBUG = True

ALLOWED_HOSTS = ['127.0.0.1']

TEST_MOBILE = []
TEST_CODE = ['123456']

INSTALLED_APPS = [
    'simpleui',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_celery_beat',  # django-celery
    'django_celery_results',  # django-celery
    'cacheops',  # 缓存模块
    'corsheaders',
    'ckeditor',  # 富文本编辑
    'django_filters',
    'qiniustorage',  # 七牛云
    'import_export',  # 数据导入导出
    'rest_framework',
    'app',
    'home',
    'money',
    'product',
    'sales',
    'vip',
    'oa',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    # 'jiaozi.middleware.JzResponseMiddleware',
]

ROOT_URLCONF = 'jiaozi.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [Path(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'jiaozi.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = False


STATIC_URL = '/static/'
STATIC_ROOT = Path(BASE_DIR, 'static')

MEDIA_ROOT = 'media/'
MEDIA_URL = "/media/"

AUTH_USER_MODEL = 'app.WxUser'

SIMPLEUI_INDEX = '/'
SIMPLEUI_STATIC_OFFLINE = True
SIMPLEUI_HOME_INFO = False
SIMPLEUI_HOME_QUICK = True
SIMPLEUI_HOME_ACTION = False
SIMPLEUI_ANALYSIS = False
SIMPLEUI_DEFAULT_ICON = False
SIMPLEUI_LOGO = 'http://qiniu.dumplingplan.cn/media/oa/202105/logo.png'

CKEDITOR_CONFIGS = {
    # django-ckeditor默认使用default配置
    'default': {
        # 编辑器宽度自适应
        'width': 'auto',
        'height': '250px',
        # tab键转换空格数
        'tabSpaces': 4,
        # 工具栏风格
        'toolbar': 'full',
    }
}

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework_simplejwt.authentication.JWTTokenUserAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DATETIME_FORMAT': '%Y-%m-%d %H:%M:%S',
    'DEFAULT_PAGINATION_CLASS': 'jiaozi.utils.NormalResultsSetPagination',
    'DEFAULT_FILTER_BACKENDS': (
        'django_filters.rest_framework.DjangoFilterBackend',
        'rest_framework.filters.OrderingFilter',
        'rest_framework.filters.SearchFilter'
    ),
    'PAGE_SIZE': 20,
    'DEFAULT_SCHEMA_CLASS': 'jiaozi.schema.ManualSchema',
    # 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(days=90),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=180),
    'ROTATE_REFRESH_TOKENS': True,
    'BLACKLIST_AFTER_ROTATION': True,

    'ALGORITHM': 'HS256',
    'SIGNING_KEY': JWT_SIGNING_KEY,
    'VERIFYING_KEY': None,

    'AUTH_HEADER_TYPES': ('Bearer', 'JWT'),
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',

    'AUTH_TOKEN_CLASSES': (
        'rest_framework_simplejwt.tokens.AccessToken',
    ),
    'TOKEN_TYPE_CLAIM': 'token_type',

    'JTI_CLAIM': 'jti',

    'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
    'SLIDING_TOKEN_LIFETIME': timedelta(days=7),
    'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=30),
}

CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'VIEW',
)

CORS_ALLOW_HEADERS = (
    'XMLHttpRequest',
    'X_FILENAME',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'Pragma',
)

X_FRAME_OPTIONS = 'SAMEORIGIN'

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}
CACHEOPS_REDIS = "redis://:password@localhost:6379/1"
CACHEOPS_DEGRADE_ON_FAILURE = True
CACHEOPS = {
    'app.WxUser': {'ops': 'get', 'timeout': 60*15},
    'app.Document': {'ops': 'all', 'timeout': 60*60},
    'product.ProductStyle': {'ops': 'get', 'timeout': 60*15},
    'product.ProductCategory': {'ops': 'get', 'timeout': 60*15},
    'product.ProductInfo': {'ops': 'get', 'timeout': 60*15},
    'vip.VipLevel': {'ops': 'all', 'timeout': 60*15},
    'vip.VipSales': {'ops': 'all', 'timeout': 1},
}

IMPORT_EXPORT_IMPORT_PERMISSION_CODE = 'add'
IMPORT_EXPORT_EXPORT_PERMISSION_CODE = 'add'
IMPORT_EXPORT_CHUNK_SIZE = 100

ACCESS_KEY_ID = '******'
ACCESS_KEY_SECRET = '******'
SMS_TEMPLATE = 'SMS_213355252'
SIGN_NAME = '******'
SMS_TEMPLATE_2 = 'SMS_219405681'

CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/"

WX_APP_ID = '******'
WX_APP_SECRET = '******'

PRIVKEY = """
-----BEGIN RSA PRIVATE KEY-----
MIICYAIBAAKBgQCF43EXrikToi40F6nFYhAhuyzJ7BhaxkLQFDy4eudcysmvWkiZ
/5V0ot4uLX5PV2K4HNFbSBaTbzudlfFe/4pPH8fI7S9aVw7+clwOjLSZTrADL7xQ
ZxuO6rd1DiOETAsxp4uRXl1A47ZgYaZi60EwRAWI6BX7FTJKjrwJMXgW6QIDAQAB
AoGAd3//KsGZjBqO3pPYRYI3H8QuP7NoMW0PqSTG5WldIyckSExuzHSgctADOngE
atB2HhoqiiyXadQ4A3kWsE9QX72TteDneUifEM9ISailX2o3zwupNv2xXYog4N05
WLqxzqtLH8mjH2H2zY/XKL2YCuBTsGh7uerH05ceH+6rMFkCRQCuynV45NKG93oV
75b3hjwZGPhNCGyrMugAtMcVkEd4VI6WHcIXX2V1f3Acm6SupFdtWaMq5FdjMBby
LFTW4WXO+LGZ3wI9AMQYEdPgB/aj7lW0D5zNjUwKjWq4Bvd4mPDWY87aEJOl+0p6
yHL1yGL5kwyhizTlp460kmmWGUEVkcD4NwJEId/Qxl4qQsfhXDDzpALa0M5bCKrS
TJdwCPr//jjY8QQKIiOgQuFVC2FoO9MaJlJpMyMFEUHxgaKHP+XBh2dlUKg32ycC
PQCMXCY2oD9S/ZgVZGNge4lOCqea4cqqzHm8udiLMW94H/C1KRndn6wlnDrzaZY4
8MF01i+OwE+nVIcVtxUCRGI2W4aT/QEDK7yagEPmDS+7z2wHqijGMh1vFK+o1q20
q5znLWCSW5MXWFTUBLXiFi0O6N1eAJ+GtGMOp3pDFPlaSO0h
-----END RSA PRIVATE KEY-----
"""

PUBKEY = """
-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBAIXjcReuKROiLjQXqcViECG7LMnsGFrGQtAUPLh651zKya9aSJn/lXSi
3i4tfk9XYrgc0VtIFpNvO52V8V7/ik8fx8jtL1pXDv5yXA6MtJlOsAMvvFBnG47q
t3UOI4RMCzGni5FeXUDjtmBhpmLrQTBEBYjoFfsVMkqOvAkxeBbpAgMBAAE=
-----END RSA PUBLIC KEY-----
"""

WECHAT = {
        'APPID': 'appid',  # 小程序ID
        'APPSECRET': 'appsecret',  # 小程序SECRET
        'MCH_ID': 'mch_id',  # 商户号
        'NOTIFY_URL': 'http://127.0.0.1:8000/wechat/payNotify/',  # 通知地址
        'TRADE_TYPE': 'JSAPI',  # 交易类型
        'API_KEY': 'merchant_key',  # 商户KEY
}


DEFAULT_FILE_STORAGE = 'qiniustorage.backends.QiniuStorage'

QINIU_ACCESS_KEY = ''
QINIU_SECRET_KEY = ''
QINIU_BUCKET_NAME = ''
QINIU_BUCKET_DOMAIN = ''
QINIU_SECURE_URL = False

CELERY_REDIS_BROKER = 'redis://@localhost:6379/1'
CELERY_TIMEZONE = TIME_ZONE
CELERY_TASK_TRACK_STARTED = True
CELERY_TASK_TIME_LIMIT = 30 * 60
DJANGO_CELERY_BEAT_TZ_AWARE = False
BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600}
CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler'

CELERY_RESULT_BACKEND = 'django-db'
CELERY_CACHE_BACKEND = 'django-cache'

# 允许root 用户运行celery
platforms.C_FORCE_ROOT = True

try:
    from .local_settings import *
except ModuleNotFoundError:
    pass
